    # -*- coding: utf-8 -*-
import threading
import time
from datetime import datetime, timedelta
from tkinter import Toplevel, Label
import tkinter as tk
from Red_black_stone import RedstoneReminder

class MealReminder:
    def __init__(self, root):
        self.running = False
        self.thread = None
        self.main_root = root
        self.redstone_reminder = RedstoneReminder(self.main_root)

    def start(self, selected_times, custom_time, advance_minutes, auto_close_seconds, redstone_enabled):
        """启动提醒服务"""
        if not self.running:
            self.running = True
            print("服务已启动")
            # 在独立线程中初始化微信绑定
            def init_wechat():
                if hasattr(self.main_root, 'wechat_reminder_var') and self.main_root.wechat_reminder_var.get():
                    print("正在初始化微信绑定...")
                    from wxauto_utils import bind_wechat
                    self.main_root.wx = bind_wechat()
                    if self.main_root.wx:
                        print("微信绑定成功")
                        from wxauto_utils import load_wechat_targets
                        self.main_root.wechat_targets = load_wechat_targets()
                        if not self.main_root.wechat_targets["friends"] and not self.main_root.wechat_targets["groups"]:
                            print("未找到微信提醒目标，请先添加。")
                    else:
                        print("微信绑定失败，无法发送微信提醒。")
            
            wechat_thread = threading.Thread(target=init_wechat, daemon=True)
            wechat_thread.start()
            
            # 启动主检查循环
            self.thread = threading.Thread(
                target=self._check_loop,
                args=(selected_times, custom_time, advance_minutes, auto_close_seconds, redstone_enabled),
                daemon=True
            )
            self.thread.start()

    def stop(self):
        """停止提醒服务"""
        self.running = False

    def _check_loop(self, selected_times, custom_time, advance_minutes, auto_close_seconds, redstone_enabled):
        """主检查循环"""
        while self.running:
            try:
                now = datetime.now()
                print(f"当前时间: {now}")
                self._check_meal_time(now, selected_times, custom_time, advance_minutes, auto_close_seconds)
                if redstone_enabled:
                    self._check_redstone(now, auto_close_seconds)
                time.sleep(60)
            except Exception as e:
                print(f"检查循环异常: {e}")
                break

    def _check_meal_time(self, now, selected_times, custom_time, advance_minutes, auto_close_seconds):
        """检查用餐时间"""
        for hour in selected_times:
            base_time = datetime(now.year, now.month, now.day, hour, 0)
            reminder_time = base_time - timedelta(minutes=advance_minutes)

            if reminder_time < now:
                reminder_time += timedelta(days=1)

            target_hhour = reminder_time.hour
            target_minute = reminder_time.minute

            print(f"预设时间 {hour} 点，提前 {advance_minutes} 分钟提醒，提醒时间为 {reminder_time}")

            if now.hour == target_hhour and now.minute == target_minute:
                print("触发预设时间提醒")
                self.show_message("亲爱的光之子，该干饭了！", auto_close_seconds)
                break

        if custom_time:
            custom_hour, custom_minute = custom_time
            print(f"自定义时间为 {custom_hour}:{custom_minute}")
            if now.hour == custom_hour and now.minute == custom_minute:
                print("触发自定义时间提醒")
                self.show_message("亲爱的光之子，到时间了！", auto_close_seconds)

    def _check_redstone(self, now, auto_close_seconds):
        """检查红石时间"""
        output = self.redstone_reminder.output_info()
        if output != "今天没有红石或黑石出现。":
            for time_range in self.redstone_reminder.get_time_ranges(
                self.redstone_reminder.weekday,
                self.redstone_reminder.is_redstone(self.redstone_reminder.today.day, self.redstone_reminder.weekday),
                self.redstone_reminder.is_blackstone(self.redstone_reminder.today.day, self.redstone_reminder.weekday)
            ):
                start_hour, start_minute = time_range
                if now.hour == start_hour and now.minute == start_minute:
                    if not self.redstone_reminder.reminded.get(time_range, False):
                        self.redstone_reminder.reminded[time_range] = True
                        self.show_message(output, auto_close_seconds)

    def show_message(self, message, auto_close_seconds):
        """显示提醒"""
        def _show():
            # 微信提醒
            print(f"调试: 检查微信提醒条件 - wechat_reminder_var存在: {hasattr(self.main_root, 'wechat_reminder_var')}")
            if hasattr(self.main_root, 'wechat_reminder_var'):
                print(f"调试: wechat_reminder_var值: {self.main_root.wechat_reminder_var.get()}")
                
            if hasattr(self.main_root, 'wechat_reminder_var') and self.main_root.wechat_reminder_var.get():
                print("微信提醒: 正在尝试发送微信提醒")
                print(f"调试: wx实例存在: {hasattr(self.main_root, 'wx')}")
                
                if hasattr(self.main_root, 'wx') and self.main_root.wx:
                    print("微信提醒: 已检测到有效的微信实例")
                    print(f"调试: wechat_targets存在: {hasattr(self.main_root, 'wechat_targets')}")
                    
                    if hasattr(self.main_root, 'wechat_targets'):
                        targets = self.main_root.wechat_targets
                        print(f"调试: 微信目标 - 好友: {targets['friends']}, 群组: {targets['groups']}")
                        
                        from wxauto_utils import send_wechat_message
                        if targets["friends"] or targets["groups"]:
                            for friend in targets["friends"]:
                                try:
                                    print(f"调试: 正在尝试发送给好友 {friend}")
                                    result = send_wechat_message(self.main_root.wx, friend, message, False)
                                    if result:
                                        print(f"微信提醒: 已发送给好友 {friend}")
                                    else:
                                        print(f"微信提醒: 发送给好友 {friend} 失败")
                                except Exception as e:
                                    print(f"微信提醒: 发送给好友 {friend} 异常: {str(e)}")
                            
                            for group in targets["groups"]:
                                try:
                                    print(f"调试: 正在尝试发送给群组 {group}")
                                    result = send_wechat_message(self.main_root.wx, group, message, True)
                                    if result:
                                        print(f"微信提醒: 已发送给群组 {group}")
                                    else:
                                        print(f"微信提醒: 发送给群组 {group} 失败")
                                except Exception as e:
                                    print(f"微信提醒: 发送给群组 {group} 异常: {str(e)}")
                        else:
                            print("微信提醒: 未设置任何好友或群组目标")
                    else:
                        print("微信提醒: 未加载微信提醒目标")
                else:
                    print("微信提醒: 微信未绑定或绑定失败")

            # 显示弹窗
            print("弹窗提醒: 正在显示提醒")
            top = Toplevel(self.main_root)
            top.title("提醒")
            top.geometry("288x162")

            frame = tk.Frame(top)
            frame.place(relx=0.5, rely=0.5, anchor="center")
            Label(frame, text=message, font=("Arial", 14)).pack()

            # 居中窗口
            top.update_idletasks()
            width = top.winfo_width()
            height = top.winfo_height()
            x = (top.winfo_screenwidth() // 2) - (width // 2)
            y = (top.winfo_screenheight() // 2) - (height // 2)
            top.geometry(f"{width}x{height}+{x}+{y}")

            # 自动关闭
            if auto_close_seconds > 0:
                top.after(auto_close_seconds * 1000, top.destroy)

        self.main_root.after(0, _show)

if __name__ == "__main__":
    reminder = MealReminder(None)
    reminder.start(
        selected_times=[datetime.now().hour],
        custom_time=None,
        advance_minutes=0,
        auto_close_seconds=5,
        redstone_enabled=False
    )
    time.sleep(60)
    reminder.stop()